package com.intelligentmeterreadingsys.otherequipment.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.location.LocationManager;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.GridView.GridMainActivity;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.httpserver.UploadHttpClient;
import com.intelligentmeterreadingsys.otherequipment.db.EquipementDao;
import com.intelligentmeterreadingsys.povo.OtherEquipmentPOVO;
import com.intelligentmeterreadingsys.povo.TypePoVo;
import com.intelligentmeterreadingsys.report.activity.OrderImageActivity;
import com.intelligentmeterreadingsys.util.BluetoothHelp;
import com.intelligentmeterreadingsys.util.CHexConver;
import com.intelligentmeterreadingsys.util.DateUtil;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import com.intelligentmeterreadingsys.util.TipHelper;
import com.intelligentmeterreadingsys.waterlist.copywater.activity.ImageSwitcherActivity;

import dbhelper.DbTableName;
import dbhelper.XmlNameHelper;

/**
 * 其它设备添加
 * 
 * @author king
 * 
 */
public class EquipementAddActivity extends Activity implements OnClickListener, BDLocationListener {

    public TextView textview1;// 纬度
    public TextView textview2;// 经度
    public EditText edit1;// 设备编号
    public EditText edit2;// 安装地址
    public EditText edit3;// 精确地址
    public EditText edit4;// 描述
    public TextView textview;// RFID编号
    public Button button1;// 定位
    public Button button2;// 读卡
    public Button button3;// 保存
    public Button button4;// 上传
    public String type;// 类型名称
    public String typeid = "0";
    public Spinner spinner;// 类型
    public Double Latitude;// 维度
    public Double Longitude;// 经度
    public List<TypePoVo> list;// 类型集合
    public String[] date = null;
    public ArrayList<String> imagepath;
    private final static int DIALOG = 1;
    private static final int REQUEST_CODE_TAKE_IMAGE = 1;
    public static final int ITEM0 = Menu.FIRST;// 系统值
    public LocationClient client;
    public long time;
    public ProgressDialog pd;
    public OtherEquipmentPOVO eq = null;
    public String id = "0";
    public boolean ismodify = false;
    public String RfidNumber = "";
    public String xieyi = "15693";
    public String readtype = "Nfc读卡";

    public BluetoothHelp bluehelp;
    public String[] readdate;
    public boolean isbluetooth = true;
    public boolean isStop = false;
    public boolean isSave = false;
    public String url = "";

    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    public boolean isNfc = false;

    public Dialog dialog = null;

    public SharedPreferenceUtil sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);
	setContentView(R.layout.other_equipment_add);
	init();

    }

    /**
     * 控件初始化
     */
    public void init() {
	sp = new SharedPreferenceUtil(this);
	mAdapter = NfcAdapter.getDefaultAdapter(EquipementAddActivity.this);

	mPendingIntent = PendingIntent.getActivity(EquipementAddActivity.this, 0, new Intent(EquipementAddActivity.this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
	IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
	try {
	    ndef.addDataType("*/*");
	    mFilters = new IntentFilter[] { ndef, };
	    mTechLists = new String[][] { new String[] { NfcV.class.getName() }, new String[] { MifareClassic.class.getName() } };

	} catch (MalformedMimeTypeException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}

	textview1 = (TextView) findViewById(R.id.other_equipment_add_latitude);
	textview2 = (TextView) findViewById(R.id.other_equipment_add_longitude);
	textview = (TextView) findViewById(R.id.other_equipment_add_rfidnumber);
	edit1 = (EditText) findViewById(R.id.other_equipment_add_number);
	edit2 = (EditText) findViewById(R.id.other_equipment_add_adds);
	edit3 = (EditText) findViewById(R.id.other_equipment_add_locationadds);
	edit4 = (EditText) findViewById(R.id.other_equipment_add_desc);
	spinner = (Spinner) findViewById(R.id.other_equipment_add_type);
	button1 = (Button) findViewById(R.id.other_equipment_add_save);
	button2 = (Button) findViewById(R.id.other_equipment_add_location);
	button3 = (Button) findViewById(R.id.other_equipment_add_delect);// 保存
	button4 = (Button) findViewById(R.id.other_equipment_add_upload);
	button1.setOnClickListener(this);
	button2.setOnClickListener(this);
	button3.setOnClickListener(this);
	button4.setOnClickListener(this);
	bluehelp = new BluetoothHelp(this);
	bluehelp.init();
	spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

	    @Override
	    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

		type = arg0.getItemAtPosition(arg2).toString();
		if (arg2 != 0) {
		    typeid = list.get(arg2 - 1).getNumber();
		}

	    }

	    @Override
	    public void onNothingSelected(AdapterView<?> arg0) {
		type = "无";
		typeid = "0";

	    }

	});
	EquipementDao dao = new EquipementDao(this);

	list = dao.queryOrderType();
	if (ismodify) {
	    getTypePosition(type);
	}

	if (list != null && list.size() > 0) {
	    date = new String[list.size() + 1];
	    if (!ismodify) {
		date[0] = "请选择";
	    }
	    for (int i = 0; i < list.size(); i++) {
		date[i + 1] = list.get(i).getName();
	    }
	} else {

	    date = new String[] { "请选择" };
	}
	dao.close();
	ArrayAdapter<String> ada = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, date);// 放数据
	ada.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	spinner.setAdapter(ada);

	client = new LocationClient(this);
	initlocation();
	client.registerLocationListener(this);
    }

    /**
     * 定位初始化
     */
    public void initlocation() {
	LocationClientOption option = new LocationClientOption();
	// 打开GPS
	option.setOpenGps(true);
	// 设置坐标类型
	option.setCoorType("bd09ll");
	option.setPriority(LocationClientOption.GpsFirst);
	// 设置产品线名称
	option.setProdName("waterSys");
	// 设置定位定时时间

	option.setScanSpan(5000);

	// 是否启用缓存定位
	option.disableCache(true);

	client.setLocOption(option);

    }

    @Override
    public void onClick(View v) {
	switch (v.getId()) {
	case R.id.other_equipment_add_location:
	    Date d = new Date();
	    time = d.getTime();
	    pd = new ProgressDialog(this);
	    pd.setMessage("扫描中.....");
	    pd.show();
	    RfidNumber = "";
	    if (!readtype.equals("Nfc读卡")) {

		bluehelp.start();
		pd.dismiss();
	    } else {
		isNfc = true;
		return;
	    }
	    isStop = true;
	    new Thread() {

		@Override
		public void run() {
		    while (isStop) {
			Date d = new Date();
			if (d.getTime() - time > 20000) {
			    isStop = false;
			    Message msg = MyHandler.obtainMessage();
			    msg.what = 2;
			    MyHandler.sendMessage(msg);
			}

			String id = "";
			if (readtype.equals("Nfc读卡")) {

			} else {

			    id = bluehelp.getRfidId();
			}
			if (!TextUtils.isEmpty(id)) {
			    isStop = false;
			    Message msg = MyHandler.obtainMessage();
			    msg.what = 1;
			    msg.obj = id;
			    MyHandler.sendMessage(msg);
			}
			try {
			    Thread.sleep(200);
			} catch (InterruptedException e) {

			    e.printStackTrace();
			}
		    }
		    super.run();
		}

	    }.start();
	    break;
	case R.id.other_equipment_add_save:

	    boolean b = openGPSSettings();
	    if (!b) {
		return;
	    }

	    initlocation();
	    pd = new ProgressDialog(this);

	    pd.setMessage("定位中...");
	    pd.show();
	    time = System.currentTimeMillis();
	    System.out.println("定位开始");
	    client.start();

	    break;
	case R.id.other_equipment_add_delect:
	    if (ismodify) {
		boolean bb = modify();
		if (bb) {
		    Toast.makeText(EquipementAddActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
		} else {
		    Toast.makeText(EquipementAddActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
		}
	    } else {
		showDialog(DIALOG);
	    }

	    break;
	case R.id.other_equipment_add_upload:
	    if (!isSave) {
		Toast.makeText(EquipementAddActivity.this, "请保存后再上传", Toast.LENGTH_SHORT).show();
		return;
	    }
	    RequestUrl r = new RequestUrl(this);

	    url = r.getUrl(RequestUrl.EQUIPEMENTADD);
	    if (ismodify) {
		url = r.getUrl(RequestUrl.EQUIPEMENTMODIFY);
	    }
	    EquipementDao dao = new EquipementDao(this);

	    if (ismodify) {
		eq = dao.queryUploadEquipment(eq.getId(), "修改", "0", null).get(0);
	    } else {
		eq = dao.queryUploadEquipment(eq.getId(), "增加", "0", null).get(0);
	    }
	    dao.close();
	    pd = new ProgressDialog(this);
	    pd.setMessage("上传中.....");
	    pd.show();
	    new Thread() {

		@Override
		public void run() {
		    Map<String, String> map1 = new HashMap<String, String>();
		    map1.put("typeid", eq.getId());
		    map1.put("date", eq.getDate());
		    map1.put("desc", eq.getDesc());
		    map1.put("adds", eq.getAdds());
		    map1.put("locationadds", eq.getLocationadds());
		    map1.put("latitude", eq.getLatitude() + "");
		    map1.put("longitude", eq.getLongitude() + "");
		    map1.put("RfidNumber", eq.getRfidNumber());
		    map1.put("number", eq.getNumber());
		    List<String> list = eq.getList();
		    Map<String, String> map2 = new HashMap<String, String>();
		    Map<File, String> map3 = new HashMap<File, String>();
		    for (int i = 0; i < list.size(); i++) {
			File f = new File(list.get(i));
			if (f.exists()) {
			    map2.put(f.getName(), "imagename");
			    map3.put(f, "imagepath");
			}
		    }
		    String respone = UploadHttpClient.uploadSubmit(url, map1, map3, map2);
		    if (respone.equals("error")) {
			Message msg = uploadHandler.obtainMessage();
			msg.what = 0;
			uploadHandler.sendMessage(msg);
		    } else {
			try {
			    JSONObject json = new JSONObject(respone);
			    String message = json.getString("message");
			    if (message.equals("yes")) {
				Message msg = uploadHandler.obtainMessage();
				msg.what = 1;
				uploadHandler.sendMessage(msg);
			    } else {
				Message msg = uploadHandler.obtainMessage();
				msg.what = 2;
				uploadHandler.sendMessage(msg);
			    }
			} catch (JSONException e1) {
			    Message msg = uploadHandler.obtainMessage();
			    msg.what = 0;
			    uploadHandler.sendMessage(msg);
			}

		    }
		    super.run();
		}

	    }.start();
	    break;
	default:
	    break;
	}

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

	menu.add(0, ITEM0 + 1, 0, "拍照");
	menu.add(0, ITEM0 + 2, 0, "图文导航");
	menu.add(0, ITEM0 + 3, 0, "读卡协议");
	menu.add(0, ITEM0 + 4, 0, "读卡方式");
	menu.findItem(ITEM0 + 1);

	return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	if (item.getItemId() == ITEM0 + 2) {
	    if (!isSave) {
		Toast.makeText(EquipementAddActivity.this, "请保存后再图文绑定", Toast.LENGTH_SHORT).show();
		return false;
	    }
	    Bundle bundle = new Bundle();
	    bundle.putString("waternumber", edit1.getEditableText().toString());
	    bundle.putString("type", "2");
	    Intent intent = new Intent(EquipementAddActivity.this, GridMainActivity.class);
	    intent.putExtras(bundle);
	    startActivity(intent);
	} else if (item.getItemId() == ITEM0 + 1) {
	    Bundle bundle = new Bundle();
	    bundle.putString("status", "4");
	    bundle.putString("classname", "EquipementAddActivity");
	    if (eq == null) {
		bundle.putString("otherid", "0");

		Intent intent = new Intent(EquipementAddActivity.this, OrderImageActivity.class);
		intent.putExtras(bundle);
		startActivityForResult(intent, REQUEST_CODE_TAKE_IMAGE);
	    } else {
		bundle.putString("otherid", eq.getId());
		Intent intent = new Intent(EquipementAddActivity.this, ImageSwitcherActivity.class);
		intent.putExtras(bundle);
		startActivity(intent);

	    }

	} else if (item.getItemId() == ITEM0 + 3) {
	    showDialog(DIALOG + 2);
	} else if (item.getItemId() == ITEM0 + 4) {
	    showDialog(DIALOG + 3);
	}
	return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	if (requestCode == REQUEST_CODE_TAKE_IMAGE) {
	    if (resultCode == RESULT_OK) {
		imagepath = data.getStringArrayListExtra("imgpath");
	    }
	}
	super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
	Dialog dialog = null;
	switch (id) {

	case DIALOG:
	    Builder builder1 = new android.app.AlertDialog.Builder(this);
	    // 设置对话框的图标
	    builder1.setIcon(R.drawable.buttondraw);
	    builder1.setTitle("确定添加新的设备？");
	    builder1.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
		    if (typeid.equals("0")) {
			Toast.makeText(EquipementAddActivity.this, "你还没选择类型！", Toast.LENGTH_LONG).show();
			return;
		    }
		    boolean b = save();
		    if (b) {
			Toast.makeText(EquipementAddActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
		    } else {
			Toast.makeText(EquipementAddActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
		    }

		}
	    });
	    builder1.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
		    finish();

		}
	    });
	    // 创建一个单选按钮对话框
	    dialog = builder1.create();
	    break;

	case DIALOG + 2:
	    builder1 = new android.app.AlertDialog.Builder(this);
	    // 设置对话框的图标
	    builder1.setIcon(R.drawable.buttondraw);
	    // 设置对话框的标题
	    builder1.setTitle("单选按钮对话框");
	    // 0: 默认第一个单选按钮被选中

	    builder1.setSingleChoiceItems(R.array.hobby, 0, new android.content.DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
		    xieyi = getResources().getStringArray(R.array.hobby)[which];

		}
	    });

	    // 添加一个确定按钮
	    builder1.setPositiveButton(" 确 定 ", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
		    if (xieyi.equals("15693")) {
			time = System.currentTimeMillis();

		    } else if (xieyi.equals("14443")) {
			time = System.currentTimeMillis();
			;
		    }
		}
	    });
	    // 创建一个单选按钮对话框
	    dialog = builder1.create();
	    break;
	case DIALOG + 3:
	    if (readtype.equals("Nfc读卡")) {
		readdate = new String[] { "Nfc读卡", "蓝牙读卡" };
	    } else {
		readdate = new String[] { "蓝牙读卡", "Nfc读卡" };
	    }

	    builder1 = new android.app.AlertDialog.Builder(this);
	    // 设置对话框的图标
	    builder1.setIcon(R.drawable.buttondraw);
	    // 设置对话框的标题
	    builder1.setTitle("读卡方式选择");
	    // 0: 默认第一个单选按钮被选中

	    builder1.setSingleChoiceItems(readdate, 0, new android.content.DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
		    readtype = readdate[which];

		}
	    });

	    // 添加一个确定按钮
	    builder1.setPositiveButton(" 确 定 ", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
		    time = System.currentTimeMillis();
		    bluehelp.start();
		}
	    });
	    // 创建一个单选按钮对话框
	    dialog = builder1.create();
	    break;
	}

	return dialog;
    }

    /**
     * 判断GPS是否存在或开启
     */
    public boolean openGPSSettings() {
	LocationManager alm = (LocationManager) getSystemService(this.LOCATION_SERVICE);

	if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {

	    return true;
	}
	Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
	Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
	startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
	return false;
    }

    @Override
    public void onReceiveLocation(BDLocation location) {
	getlocation(location);
    }

    @Override
    public void onReceivePoi(BDLocation location) {
	// TODO Auto-generated method stub

    }

    /**
     * 定位
     * 
     * @param location
     */
    public void getlocation(BDLocation location) {
	if (location.getLocType() == 61) {
	    client.stop();
	    textview1.setText("纬度:" + location.getLatitude());
	    textview2.setText("经度：" + location.getLongitude());
	    Latitude = location.getLatitude();
	    Longitude = location.getLongitude();
	    Toast.makeText(this, "定位成功", Toast.LENGTH_LONG).show();
	    TipHelper.Vibrate(this, 1000);
	    sp.insertValue(XmlNameHelper.GPSLATITUDE, location.getLatitude() + "");
	    sp.insertValue(XmlNameHelper.GPSLONGITUDE, location.getLongitude() + "");
	    sp.insertValue(XmlNameHelper.GPSDATE, System.currentTimeMillis() + "");

	} else {
	    client.stop();
	    showDialog();
	    TipHelper.Vibrate(this, 1000);
	}
    }

    @Override
    protected void onDestroy() {
	if (client != null && client.isStarted()) {
	    client.stop();
	}
	bluehelp.stop();
	super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
	if (keyCode == KeyEvent.KEYCODE_BACK) {
	    if (pd != null) {
		if (pd.isShowing()) {
		    pd.dismiss();
		}
	    }
	    if (client != null && client.isStarted()) {
		client.stop();
	    }
	}
	return super.onKeyDown(keyCode, event);
    }

    /**
     * 添加其它设备
     * 
     * @return
     */
    public boolean save() {
	boolean b = false;
	OtherEquipmentPOVO e = new OtherEquipmentPOVO();
	e.setAdds(edit2.getEditableText().toString());
	e.setDesc(edit4.getEditableText().toString());
	e.setLocationadds(edit3.getEditableText().toString());
	e.setNumber(edit1.getEditableText().toString());
	e.setTypename(type);
	e.setTypeid(typeid);
	e.setList(imagepath);
	e.setLongitude(Longitude);
	e.setLatitude(Latitude);
	e.setRfidNumber(RfidNumber);
	EquipementDao dao = new EquipementDao(this);
	id = dao.insertEquipement(e);
	if (!id.equals("0")) {
	    b = true;
	}
	eq = dao.queryOne(id, null);
	isSave = true;

	dao.close();

	return b;
    }

    /**
     * 修改时交换类型位置
     * 
     * @param type
     * @return
     */
    public int getTypePosition(String type) {
	if (list != null && list.size() > 0) {
	    for (int k = 0; k < list.size(); k++) {
		if (list.get(k).getName().equals(type)) {
		    spinner.setSelection(k + 1, true);
		    return k;
		}
	    }
	}
	return 0;

    };

    /**
     * 读卡消息
     */
    public Handler MyHandler = new Handler() {

	@Override
	public void handleMessage(Message msg) {
	    if (msg.what == 1) {
		isStop = false;
		if (readtype.equals("Nfc读卡")) {
		    pd.dismiss();
		} else {
		    bluehelp.close();
		}

		TipHelper.Vibrate(EquipementAddActivity.this, 1000);
		textview.setText(msg.obj.toString());

		RfidNumber = msg.obj.toString();
		EquipementDao dao = new EquipementDao(EquipementAddActivity.this);
		OtherEquipmentPOVO e = dao.queryOne(null, RfidNumber);
		dao.close();
		if (e != null) {
		    Toast.makeText(EquipementAddActivity.this, "此RFID已绑定了设备", Toast.LENGTH_SHORT).show();
		    eq = e;

		    ismodify = true;
		    initmodify();
		    viewdate();
		    if (e.getIsadd().equals("新增")) {
			edit1.setEnabled(true);
		    } else {
			edit1.setEnabled(false);
		    }
		}
	    } else {
		isStop = false;
		Toast.makeText(EquipementAddActivity.this, "读卡超时", 1000).show();
		if (readtype.equals("终端读卡")) {
		    pd.dismiss();
		} else {
		    bluehelp.close();
		}

	    }
	}

    };

    /**
     * 当RFID已绑定设备时调用
     */
    public void initmodify() {
	this.Latitude = eq.getLatitude();
	this.Longitude = eq.getLongitude();
	this.RfidNumber = eq.getRfidNumber();
	this.type = eq.getTypename();
	getTypePosition(type);
    }

    public void viewdate() {
	edit1.setText(eq.getNumber());
	edit2.setText(eq.getAdds());
	edit3.setText(eq.getLocationadds());
	edit4.setText(eq.getDesc());
	textview.setText(eq.getRfidNumber());
	textview1.setText("维度:" + eq.getLatitude());
	textview2.setText("经度:" + eq.getLongitude());
    }

    /**
     * 修改
     * 
     * @return
     */
    public boolean modify() {
	boolean b = false;
	ContentValues values = new ContentValues();
	values.put("ep_number", edit1.getText().toString());
	values.put("latitude", Latitude);
	values.put("longitude", Longitude);
	values.put("RfidNumber", RfidNumber);
	values.put("ep_typename", type);
	values.put("ep_type", typeid);
	values.put("ep_adds", edit2.getText().toString());
	values.put("ep_locationadds", edit3.getText().toString());
	values.put("ep_dess", edit4.getText().toString());
	if (eq == null) {
	    values.put("isadd", "增加");
	} else if (eq != null && eq.getIsupload().equals("0")) {
	    values.put("isadd", "增加");
	} else {
	    values.put("isadd", "修改");
	}

	values.put("isupload", "0");
	EquipementDao dao = new EquipementDao(this);
	b = dao.modify(eq.getId(), DbTableName.EQUIPEMENT, values);
	eq = dao.queryOne(id, null);
	dao.close();
	return b;
    }

    /**
     * 上传消息
     */
    Handler uploadHandler = new Handler() {

	@Override
	public void handleMessage(Message msg) {

	    pd.dismiss();
	    if (msg.what == 0) {
		Toast.makeText(EquipementAddActivity.this, "网络连接错误", Toast.LENGTH_SHORT).show();
	    } else if (msg.what == 2) {
		Toast.makeText(EquipementAddActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
	    } else if (msg.what == 1) {
		EquipementDao dao = new EquipementDao(EquipementAddActivity.this);
		dao.modifyEquiPement(eq.getId());
		dao.close();
		Toast.makeText(EquipementAddActivity.this, "上传成功", Toast.LENGTH_SHORT).show();

	    }
	}

    };

    @Override
    protected void onPause() {

	mAdapter.disableForegroundDispatch(this);

	super.onPause();
    }

    @Override
    protected void onResume() {
	mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);

	super.onResume();
    }

    @Override
    protected void onNewIntent(Intent intent) {
	if (!isNfc) {
	    return;
	}

	if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
	    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
	    for (String tech : tagFromIntent.getTechList()) {
		System.out.println(tech);
	    }
	    time = System.currentTimeMillis();
	    MifareClassic mf = MifareClassic.get(tagFromIntent);
	    if (mf != null) {

		boolean auth = false;
		try {
		    mf.connect();
		    auth = mf.authenticateSectorWithKeyA(0, MifareClassic.KEY_DEFAULT);// 获取第一个扇区权限
		    if (auth) {
			byte[] date = mf.readBlock(0);// 读取block 0
			RfidNumber = CHexConver.bytesToHexStrings(date);
			Message msg = MyHandler.obtainMessage();
			msg.what = 1;
			msg.obj = RfidNumber;
			MyHandler.sendMessage(msg);
		    }

		} catch (IOException e) {

		    e.printStackTrace();
		} finally {
		    try {
			mf.close();
		    } catch (IOException e) {

			e.printStackTrace();
		    }
		}

	    }
	    NfcV nf = NfcV.get(tagFromIntent);
	    if (nf != null) {
		RfidNumber = CHexConver.bytesToHexStrings(nf.getTag().getId());
		Message msg = MyHandler.obtainMessage();
		msg.what = 1;
		msg.obj = RfidNumber;
		MyHandler.sendMessage(msg);
	    }

	}

	super.onNewIntent(intent);
    }

    public void showDialog() {

	String message = "";
	if (sp.getValue(XmlNameHelper.GPSDATE).equals("0")) {
	    message = "还没有定位成功过！";
	} else {
	    long ti = System.currentTimeMillis() - Long.parseLong(sp.getValue(XmlNameHelper.GPSDATE));

	    message = "最近一次定位时间在:" + DateUtil.getMuntion(ti);
	}

	Builder builder = new android.app.AlertDialog.Builder(this);
	// 设置对话框的图标
	builder.setIcon(R.drawable.buttondraw);
	// 设置对话框的标题

	builder.setMessage(message);

	// 添加一个确定按钮
	builder.setPositiveButton(" 确 定 ", new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
		textview2.setText("纬度:" + sp.getValue(XmlNameHelper.GPSLATITUDE));
		textview1.setText("经度：" + sp.getValue(XmlNameHelper.GPSLONGITUDE));
		Latitude = Double.parseDouble(sp.getValue(XmlNameHelper.GPSLATITUDE));
		Longitude = Double.parseDouble(sp.getValue(XmlNameHelper.GPSLONGITUDE));

	    }
	});
	builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {

	    @Override
	    public void onClick(DialogInterface dialog, int which) {
		textview2.setText("纬度:" + 0.0);
		textview1.setText("经度：" + 0.0);
		Latitude = 0.0;
		Longitude = 0.0;

	    }
	});
	// 创建一个单选按钮对话框
	dialog = builder.create();
	dialog.show();

    }
}
